package com.wxmit.module.system.service;


import cn.hutool.core.lang.Dict;
import com.wxmit.base.util.JsonUtils;
import com.wxmit.module.system.api.GDHttpApi;
import com.wxmit.starter.cache.api.CacheApi;
import com.wxmit.starter.cache.domain.CacheTime;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;


@Service
@RequiredArgsConstructor
public class GdWeatherService {

    private final GDHttpApi gdHttpApi;

    private final CacheApi cacheApi;

    @Value("${gd.weather.key}")
    private String key;

    @Value("${gd.weather.city}")
    private String cityCode;

    private final String CACHE_KEY = "shushan:gd:weather";

    /**
     *  获取高德的live天气，cache 3小时失效一次
     */
    public  Object getLiveWeatherByGd(){
        Optional<Object> resultOpt = cacheApi.get(CACHE_KEY);
        if(resultOpt.isPresent()){
            return resultOpt.get();
        }
        synchronized (this){
            resultOpt = cacheApi.get(CACHE_KEY);
            if(resultOpt.isPresent()){
                return resultOpt.get();
            }
            String result = gdHttpApi.getByCity(key,cityCode);
            Dict dict = JsonUtils.parseMap(result);
            List forecasts = (List) dict.get("forecasts");
            Map map = (Map) forecasts.get(0);
            Object val = map.get("casts");
            cacheApi.set(CACHE_KEY,result);
            cacheApi.expire(CACHE_KEY,new CacheTime(3, TimeUnit.HOURS));
            return val;
        }

    }

}
